package com.cennavi.minenavidemo.activity;

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.widget.Toast;

import androidx.annotation.StringRes;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.cennavi.minenavidemo.R;
import com.cennavi.minenavidemo.adapter.FeatureAdapter;
import com.cennavi.minenavidemo.adapter.FeatureSectionAdapter;
import com.cennavi.minenavidemo.utils.Config;
import com.cennavi.minenavidemo.utils.Feature;
import com.cennavi.minenavidemo.utils.ItemClickSupport;
import com.cennavi.minenavidemo.utils.ScreenUtil;
import com.minedata.minenavi.SDKInitializer;
import com.minedata.minenavi.map.MineMap;
import com.minedata.minenavi.mapdal.NativeEnv;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;


public class MainActivity extends CheckPermissionsActivity {
    private static final String KEY_STATE_FEATURES = "featureList";

    private RecyclerView recyclerView;
    private FeatureSectionAdapter sectionAdapter;
    private List<Feature> features;
    private int locationActivityInList;
    private boolean isAuthorization = false;//是否授权 true授权过 false没授权过

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.addOnItemTouchListener(new RecyclerView.SimpleOnItemTouchListener());
        recyclerView.setHasFixedSize(true);


        ItemClickSupport.addTo(recyclerView).setOnItemClickListener((recyclerView, position, view) -> {
            if (!sectionAdapter.isSectionHeaderPosition(position)) {
                int itemPosition = sectionAdapter.getConvertedPosition(position);
                Feature feature = features.get(itemPosition);

                if (feature.isRequiresLocationPermission()) {
                    if (requestLocationPermission(itemPosition)) {
                        return;
                    }
                }

                startFeature(feature);
            }
        });

        if (savedInstanceState == null) {
            loadFeatures();
        } else {
            features = savedInstanceState.getParcelableArrayList(KEY_STATE_FEATURES);
            onFeaturesLoaded(features);
        }
        ScreenUtil.getInstance().init(this, getWindow());
    }

    @Override
    public void permissionsResultOK() {
        if (!isAuthorization)
            init();
    }

    private void init() {
        SDKInitializer.setUseSimLocation(Config.isUseSimLocation);

        if (SDKInitializer.getServerHost().equals("mineservice.minedata.cn")) {
            SDKInitializer.setServerHost("mineservice.minedata.cn/service/lbs");
            SDKInitializer.setSearchUrl("http://mineservice.minedata.cn/service/lbs/");
            SDKInitializer.setInverseUrl("http://mineservice.minedata.cn/service/lbs/");
            SDKInitializer.setStyleUrl(MineMap.UrlType.basicMap, "http://mineservice.minedata.cn/service/lbs/nc/v1/tile/v2");
        }

        SDKInitializer.initialize(this, new SDKInitializer.InitListener() {
            @Override
            public void onInitSuccess() {
                int a = NativeEnv.getNetworkStatus();
                Toast.makeText(MainActivity.this, "SDK初始化成功,NetworkStatus:"+a, Toast.LENGTH_LONG).show();
                isAuthorization = true;
            }

            @Override
            public void onInitFailed(String msg) {
                Toast.makeText(MainActivity.this, msg, Toast.LENGTH_LONG).show();
            }
        });
    }

    private void startFeature(Feature feature) {
        Intent intent = new Intent();
        intent.setComponent(new ComponentName(getPackageName(), feature.getName()));
        startActivity(intent);
    }

    private boolean isRuntimePermissionsRequired() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M;
    }

    private boolean requestLocationPermission(final int positionInList) {
        if (isRuntimePermissionsRequired()) {
            locationActivityInList = positionInList;
            return true;
        }

        return false;
    }


    private void loadFeatures() {
        try {
            new LoadFeatureTask().execute(
                    getPackageManager().getPackageInfo(getPackageName(),
                            PackageManager.GET_ACTIVITIES | PackageManager.GET_META_DATA));
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }


    private void onFeaturesLoaded(List<Feature> featuresList) {
        features = featuresList;

        List<FeatureSectionAdapter.Section> sections = new ArrayList<>();
        String currentCat = "";

        for (int i = 0; i < features.size(); i++) {
            String category = features.get(i).getCategory();

            if (!currentCat.equals(category)) {
                sections.add(new FeatureSectionAdapter.Section(i, category));
                currentCat = category;
            }
        }

        FeatureSectionAdapter.Section[] dummy = new FeatureSectionAdapter.Section[sections.size()];
        sectionAdapter = new FeatureSectionAdapter(
                this, R.layout.section_main_layout, R.id.section_text, new FeatureAdapter(features));
        sectionAdapter.setSections(sections.toArray(dummy));
        recyclerView.setAdapter(sectionAdapter);
    }


    @SuppressLint("StaticFieldLeak")
    private class LoadFeatureTask extends AsyncTask<PackageInfo, Void, List<Feature>> {

        @Override
        protected List<Feature> doInBackground(PackageInfo... params) {
            List<Feature> features = new ArrayList<>();
            PackageInfo app = params[0];
            String packageName = getApplicationContext().getPackageName();
            String metaDataKey = getString(R.string.category);

            for (ActivityInfo info : app.activities) {
                if (info.labelRes != 0 && info.name.startsWith(packageName)
                        && !info.name.equals(MainActivity.class.getName())) {
                    String label = getString(info.labelRes);
                    String description = resolveString(info.descriptionRes);
                    String category = resolveMetaData(info.metaData, metaDataKey);
                    boolean requiresLocationPermission = requiresLocationPermission(label, category);
                    features.add(new Feature(info.name, label, description, category, requiresLocationPermission));
                }
            }

//            if (!features.isEmpty()) {
//                Comparator<Feature> comparator = (lhs, rhs) -> {
//
//                    int result = lhs.getCategory().compareToIgnoreCase(rhs.getCategory());
//
//                    if (result == 0) {
//                        result = lhs.getLabel().compareToIgnoreCase(rhs.getLabel());
//                    }
//
//                    return result;
//                };
//
//                Collections.sort(features, comparator);
//            }

            return features;
        }

        private String resolveMetaData(Bundle bundle, String key) {
            String category = null;

            if (bundle != null) {
                category = bundle.getString(key);
            }

            return category;
        }

        private String resolveString(@StringRes int stringRes) {
            try {
                return getString(stringRes);
            } catch (Resources.NotFoundException exception) {
                return "-";
            }
        }

        private boolean requiresLocationPermission(String name, String category) {
            final Resources resources = getResources();

            List<String> requiresPermissionCategories = new ArrayList<String>() {
                {
//                    add(resources.getString(R.string.category_userlocation));
                }
            };

            List<String> requiresPermissionActivities = new ArrayList<String>() {
                {
//                    add(resources.getString(R.string.activity_double_map));
                }
            };

            return requiresPermissionCategories.contains(category) || requiresPermissionActivities.contains(name);
        }

        @Override
        protected void onPostExecute(List<Feature> features) {
            super.onPostExecute(features);
            onFeaturesLoaded(features);
        }
    }
}
